package com.ctgu.project03.interceptor;

import com.ctgu.project03.utils.BaseContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @ClassName TokenInterceptor
 * @Author Alex2
 * @Date 2025/2/26 11:02
 **/
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断ThreadLocal中是否有用户 ，没有则拦截
        if (BaseContext.get() == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            errorResponse(response);
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.remove();        // 移除用户
    }

    public void errorResponse(HttpServletResponse response) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg", "token无效");
        map.put("code", HttpServletResponse.SC_UNAUTHORIZED);
        map.put("data", null);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    }
}
